package thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPool{

    private BlockingQueue<Runnable> queue = null;
    // 初始化线程池，创建固定数量的线程
    public MyThreadPool(int n){
        // 使用ArrayBlockingQueue作为任务队列，容量为1000
        // 阻塞队列天然线程安全，因此直接编写任务主体逻辑
        queue = new ArrayBlockingQueue<Runnable>(1000);
        // 创建n个线程
        for (int i = 0; i < 1000; i++) {
            Thread thread = new Thread(()->{
               while(true){
                   // 不断尝试从任务队列中取任务进行操作
                   try {
                       Runnable task = queue.take();
                       task.run();
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
            });
            thread.start();
        }
    }

    // 把任务添加到队列中
    public void submit(Runnable task) throws InterruptedException {
        queue.put(task);
    }


}
public class Demo26 {
    public static void main(String[] args) throws InterruptedException {

        MyThreadPool threadPool = new MyThreadPool(100);
        // 向线程池提交任务
        for (int i = 0; i < 100; i++) {
            int id = i;
            threadPool.submit(()->{
                System.out.println(Thread.currentThread().getName() + id + ":running...");
            });
        }
    }
}
